package cc.ug_project.rollcall.Bussness.DataModel

import cn.bmob.v3.Bmob
import cn.bmob.v3.BmobObject
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import cn.bmob.v3.listener.SaveListener
import cn.bmob.v3.listener.UpdateListener

/**
 * Created by yeganaaa on 4/3/18.
 */

fun BmobObject.save(action: (objectId: String, exception: BmobException?) -> Unit) {
    this.save(object : SaveListener<String>() {
        override fun done(p0: String, p1: BmobException?) {
            action(p0, p1)
            p1?.printStackTrace()
        }
    })
}

fun BmobObject.update(action: (exception: BmobException?) -> Unit) {
    this.update(object : UpdateListener() {
        override fun done(p0: BmobException?) {
            action(p0)
        }
    })
}

fun <T> BmobQuery<T>.findObjects(action: (objects: List<T>, exception: BmobException?) -> Unit){
    this.findObjects(object: FindListener<T>(){
        override fun done(p0: List<T>, p1: BmobException?) {
            action(p0, p1)

            p1?.printStackTrace()
        }
    })
}


/*For USer*/

fun User.getPermission(bit: Int): Boolean = ((1 shl bit) and 0xff) > 0

/**
 ~(1 < 3 = 0000 1000) = 1111 0111

 */
fun User.setPermission(bit: Int, value: Boolean) {
    if (value)
        this.permissions = this.permissions or (1 shl bit) // |= 1 << bit
    else
        this.permissions = this.permissions and (1 shl bit).inv() // &= ~(1 << bit)
}

var User.canSignIn: Boolean
    get() = getPermission(User.CAN_SIGNIN)
    set(value) {
        setPermission(User.CAN_SIGNIN, value)
    }